package com.diaohw.module.log.service.export;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.WorkbookUtil;
import com.diaohw.module.log.obj.entity.RequestLog;
import com.diaohw.platform.framework.web.util.RequestUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ExcelHandle {


    public void execute(List<RequestLog> rows) throws IOException {

        Map<String, List<RequestLog>> collect = rows.stream().collect(Collectors.groupingBy(requestLog -> DateUtil.format(requestLog.getCreatedTime(), DatePattern.NORM_MONTH_PATTERN)));
        Workbook book = WorkbookUtil.createBook(Boolean.TRUE);

        collect.forEach((sheetName, value) -> {
            Sheet sheet = book.createSheet(sheetName);
            writeSheet(sheet, value);
        });

        book.write(RequestUtil.getResponse().getOutputStream());
        book.close();
    }

    private static final String[] title = {"请求IP地址", "登录账户", "登录用户昵称", "操作描述", "请求时间"};

    private void writeSheet(Sheet sheet, List<RequestLog> rows) {
        int rowNum = 0;

        Row titleRow = sheet.createRow(rowNum++);

        for (int i = 0; i < title.length; i++) {
            titleRow.createCell(i).setCellValue(title[i]);
        }

        for (RequestLog log : rows) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(log.getRequestIp());
            row.createCell(1).setCellValue(log.getLoginUsername());
            row.createCell(2).setCellValue(log.getLoginNickname());
            row.createCell(3).setCellValue(log.getDescription());
            row.createCell(4).setCellValue(DateUtil.format(log.getRequestTime(), DatePattern.NORM_DATETIME_MS_PATTERN));
        }


    }


}
